#include "common.h"
void sys_init();
void sys_end();
void usr_app();
void Ctrl_C(int source);
void AXI_init();
#if !MODULE_TEST
void AXI_Test(int val, int addr);
void AXIC_Test(int val, int addr);
#endif
int openOne_TRXModule(int channel);
extern int system_status;
extern const uint8 *local_ip;
extern const uint8 *local_ip_port;
extern uint8 ParaModule;
extern uint8 ParaVal;
int main(int argc, char const *argv[]) {
    // signal(SIGSEGV, ctrace);
    signal(SIGINT, Ctrl_C);
    LOG_INFO("The program compile time is: "__DATE__" "__TIME__"");
#ifdef COMPILE_INCRE
    LOG_DEBUG("TEST COMPILE INCRE");
    exit(1);
#endif  

#if !MODULE_TEST
    if(argc != 3 && argc != 4) {
        LOG_ERROR("para error:");
        LOG_INFO("if network  module, eg: \"./a.out {localIP} {port}\" exp \"./a.out 192.168.0.50 5555\"");
        LOG_INFO("if test RTX module, eg: \"./a.out T {hexval} {channel}\" exp \"./a.out R 80 12\"");
        LOG_INFO("if test AXI module, eg: \"./a.out A {val} {addr}\" exp \"./a.out A 10 1\"");
        LOG_INFO("if test AXI module, eg: \"./a.out C {val} {addr}\" exp \"./a.out C 10 1\"");
        exit(-1);
    }
    
    if(argv[1][0] == 'A'){
        AXI_init();
        int para1 = atoi(argv[2]);
        int para2 = atoi(argv[3]);
        AXI_Test(para1, para2);
        exit(0);
    } else if(argv[1][0] == 'C'){
        AXI_init();
        int para1 = atoi(argv[2]);
        int para2 = atoi(argv[3]);
        AXIC_Test(para1, para2);
        exit(0);
    } else if(argv[1][0] == 'T') {
        ParaModule = Para_TX_COMP;
    } else if(argv[1][0] == 'R') {
        ParaModule = Para_RX_COMP;
    } else {
        ParaModule = Para_NETWORK;
    }
    if(ParaModule != Para_NETWORK) {
        int OpenChannel = atoi(argv[3]);
        char *temp;
        ParaVal = strtol(argv[2], &temp, 16);
        if(!(OpenChannel >= 1 && OpenChannel <= 128)) {
            LOG_ERROR("channel rang is [1~128], but open channel is %d, val %02x", OpenChannel, ParaVal);
            exit(-1);
        }
        LOG_INFO("start open channel %sx Module, open channel %d, val %02x", argv[1], OpenChannel, ParaVal);
        AXI_init();
        openOne_TRXModule(OpenChannel);
        exit(0);
    }

    local_ip = argv[1];
    local_ip_port = argv[2];
#else
    local_ip = "127.0.0.1";
    local_ip_port = "5555";
#endif
    sys_init();
    usr_app();
    prctl(PR_SET_NAME, "Main");
    while (1) {
        if(system_status == END___PROGRAM) {
            // 结束程序的话, 需要做哪些事
            sys_end();
            exit(0);
        }
        sleep(1);
    }
    return 0;
}
